<template>
  <div class="v-sexage-ratio">
    <Row :gutter="0">
        <Col span="12">
          <Card :bordered="false" :dis-hover="true" :shadow="true">
              <p slot="title">年龄比例</p>
            <div id="chartAge"></div>
          </Card>
        </Col>
        <Col span="12">
            <Card :bordered="false" :dis-hover="true" :shadow="true">
              <p slot="title">性别比例</p>
              <div slot="extra">
                  <Dropdown trigger="custom" :visible="visible" class="v-dropdown" @on-clickoutside="handleClose" style="min-width: 240px;" placement="top-end">
                    <span @click="handleOpen">
                        门店筛选
                        <Icon type="arrow-down-b"></Icon>
                    </span>
                    <DropdownMenu slot="list">
                        <CheckboxGroup v-model="areaNameCheck">
                            <Checkbox v-for="(item, index) in searchAreas" :label="item.areaName" :key="index"></Checkbox>
                        </CheckboxGroup>
                        <div style="text-align: right; margin:10px;">
                            <Button type="primary" @click="handleSubmit">确定</Button>
                        </div>
                    </DropdownMenu>
                  </Dropdown>
              </div>
              <div id="chartSex"></div>
          </Card>
        </Col>
    </Row>
  </div>
</template>

<script>
import { mapState } from 'vuex'
var echarts = require('echarts/lib/echarts');
require('echarts/lib/chart/pie');
// 引入提示框和标题组件
require('echarts/lib/component/tooltip');
require('echarts/lib/component/title');
require('echarts/lib/component/legend');

export default {
  name: "v-sexage-ratio",
  props: {
  },
  data () {
    return {
      ageSexualStoreData: {},
      searchAreas: [],
      areaName: '',
      areaCode: '',
      visible: false,
      areaNameCheck: [],
      myChart1: null,
      myChart2: null
    }
  },
  computed: {
    ...mapState({
      sideBarWidth: state => state.sideBarWidth,
      getAjaxParams: state => state.timeParams
    })
  },
  watch: {
    getAjaxParams(val) {
      if (this.areaCode !== '') {
        this.AgeSexualStoreData(Object.assign({}, val, {areaCodes: this.areaCode}))
        this.$store.dispatch('SetDownLink', Object.assign({}, val, {areaCodes: this.areaCode}))
      }
    },
    sideBarWidth (val) {
      setTimeout(() => {
        this.myChart1.resize()
        this.myChart2.resize()
      }, 200)
    }
  },
  created () {
    this.SearchAreas()
  },
  methods: {
    AgeSexualStoreData (params) {
      this.$store.dispatch('AgeSexualStoreData', params).then((res) => {
          if (res.success === '1') {
            this.ageSexualStoreData = res.data
            let seriesAge = []
            let legendAge = []
            let ageDec = ['0-18岁', '19-30岁', '31-40岁', '41-50岁', '51岁以上']
            let age = [this.ageSexualStoreData.age1, this.ageSexualStoreData.age2, this.ageSexualStoreData.age3, this.ageSexualStoreData.age4, this.ageSexualStoreData.age5]
            for (var i = 0; i < ageDec.length; i++) {
              legendAge.push({
                name: ageDec[i],
                value: age[i]
              })
              seriesAge.push({
                name: ageDec[i],
                value: age[i]
              })
            }
            let seriesSex = []
            let legendSex = []
            let SexDec = ['男性', '女性']
            let sex = [this.ageSexualStoreData.males, this.ageSexualStoreData.females]
            for (var i = 0; i < SexDec.length; i++) {
              legendSex.push({
                name: SexDec[i],
                value: sex[i]
              })
              seriesSex.push({
                name: SexDec[i],
                value: sex[i]
              })
            }
            this.$nextTick(() => {
              this.drawChartPie('chartAge', legendAge, seriesAge)
              this.drawChartPie2('chartSex', legendSex, seriesSex)
            })
          }
      })
    },
    drawChartPie (id, legend, series) {
      // 基于准备好的dom，初始化echarts实例
      this.myChart1 = echarts.init(document.getElementById(id));
      // 绘制图表
      this.myChart1.setOption({
        tooltip: {
          trigger: 'item',
          formatter: "{b}: {c} ({d}%)"
        },
        legend: {
          show: true,
          x: 'left',
          y: 'center',
          left: 20,
          padding: [30, 10],
          itemGap: 20,
          itemWidth: 8,
          itemHeight: 8,
          orient: 'vertical',
          data: legend,
          formatter: (name) => {
            var total = 0;
            var target;
            for (var i = 0, l = legend.length; i < l; i++) {
              total += legend[i].value;
              if (legend[i].name == name) {
                target = legend[i].value;
              }
            }
            var arr = [
              '{b|' + name + '}',
              '{a|' + ((target/total)*100).toFixed(2) + '%}'
            ]
            return arr.join('')
          },
          textStyle:{
            rich: {
                b: {
                    width: 90
                }
            }
          }
        },
        series: [
          {
            color: ['#2497fc', '#ff9e4f', '#4bc9b6', '#916ff3', '#f14b79'],
            name:'',
            type:'pie',
            radius: ['22%', '45%'],
            center: ['60%', '50%'],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false,
                position: 'center'
              },
              emphasis: {
                show: true,
                textStyle: {
                  fontSize: '30',
                  fontWeight: 'bold'
                }
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: series
          }
        ]
      }, true)
      setTimeout(() => {
        window.onresize = this.myChart1.resize
      }, 200)
    },
    drawChartPie2 (id, legend, series) {
      // 基于准备好的dom，初始化echarts实例
      this.myChart2 = echarts.init(document.getElementById(id));
      // 绘制图表
      this.myChart2.setOption({
        tooltip: {
          trigger: 'item',
          formatter: "{b}: {c} ({d}%)"
        },
        legend: {
          show: true,
          x: 'left',
          y: 'center',
          left: 20,
          padding: [30, 10],
          itemGap: 20,
          itemWidth: 8,
          itemHeight: 8,
          orient: 'vertical',
          data: legend,
          formatter: (name) => {
            var total = 0;
            var target;
            for (var i = 0, l = legend.length; i < l; i++) {
              total += legend[i].value;
              if (legend[i].name == name) {
                target = legend[i].value;
              }
            }
            var arr = [
              '{b|' + name + '}',
              '{a|' + ((target/total)*100).toFixed(2) + '%}'
            ]
            return arr.join('')
          },
          textStyle:{
            rich: {
                b: {
                    width: 90
                }
            }
          }
        },
        series: [
          {
            color: ['#2497fc', '#f14b79'],
            type:'pie',
            radius: ['22%', '45%'],
            center: ['60%', '50%'],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false,
                position: 'center'
              },
              emphasis: {
                show: true,
                textStyle: {
                  fontSize: '30',
                  fontWeight: 'bold'
                }
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: series
          }
        ]
      }, true)
      setTimeout(() => {
        window.onresize = this.myChart2.resize
      }, 200)
    },
    SearchAreas () {
      this.$store.dispatch('SearchAreas').then((res) => {
        if (res.success === '1') {
          this.searchAreas = res.data
          let _areaNameCheck = []
          let _areaCode = []
          this.searchAreas.map((item) => {
            _areaNameCheck.push(item.areaName)
            _areaCode.push(item.areaCode)
          })
          this.areaNameCheck = _areaNameCheck
          this.areaCode = _areaCode.join(',')
          this.areaName = this.areaNameCheck.join(',')
          this.AgeSexualStoreData(Object.assign({}, this.$store.state.timeParams, {areaCodes: this.areaCode}))
          this.$store.dispatch('SetDownLink', Object.assign({}, this.$store.state.timeParams, {areaCodes: this.areaCode}))
        }
      })
    },
    handleOpen () {
      this.visible = true
    },
    handleClose () {
      this.visible = false
    },
    handleSubmit () {
      let _areaCode = []
      this.areaNameCheck.map((item) => {
        this.searchAreas.map((subItem) => {
          if (item === subItem.areaName) {
            _areaCode.push(subItem.areaCode)
          }
        })
      })
      this.areaName = this.areaNameCheck.join(',')
      this.areaCode = _areaCode.join(',')
      this.AgeSexualStoreData(Object.assign({}, this.$store.state.timeParams, {areaCodes: this.areaCode}))
      this.$store.dispatch('SetDownLink', Object.assign({}, this.$store.state.timeParams, {areaCodes: this.areaCode}))
      this.visible = false
    }
  }
};
</script>

<style lang="less">
.v-sexage-ratio {
  width: 100%;
  border-radius: 4px;
  margin: 0 -6px;
  background-color: #fff;
  .v-dropdown {
    text-align: right
  }
  .ivu-dropdown-menu {
    width: 240px;
    padding: 10px 15px;
  }
  .ivu-checkbox-group {
    text-align: left;
  }
  .ivu-card-head p, .ivu-card-head-inner {
    height: 32px;
    line-height: 32px;
    font-size: 24px;
  }
  .ivu-card-head {
    padding: 30px 20px;
    border-bottom: none;
  }
  .ivu-card-shadow {
    box-shadow: none;
  }
}
#chartAge {
  width: 100%;
  height: 580px;
  background-color: #f7f9fa;
}
#chartSex {
  width: 100%;
  height: 580px;
  background-color: #f7f9fa;
}
</style>
